import { setBrowse } from '@/api/borwse/borwse';
import { getDraggableNumber } from './getRemComputed';
import router from '../router/index';
const filterHTML = (input: string) => {
  // if (input) {
  //   let str = input.replace(/(<([^>]+)>)/gi, '');
  //   return str.replace(/(\r?\n)+/g, '\n');
  // } else { 
  //   return input; 
  // } 
  if (!input) { 
    return;
  }
  let arr = input.split('\n');
  let text = '';
  arr.forEach((el, index) => {
    if (el && index !== 0) {
      text = text + `\n      ${el}`;
    } else {
      text = text + `${el}`;
    }
  });
  return text; // router.push({ path: '/login' });
};

const addBrowseTemplate = (e: any, type?: number) => {
  setBrowse({
    refType: type ? type : 3,
    refId: e,
  });
};

const getTextHtml = (e: string | null): any => {
  //获取文本域转换成标签
  if (!e) {
    return;
  }
  let arr = e.split('\n');
  let text = '';
  arr.forEach((el) => {
    if (el) {
      text = text + `<p>${el}</p>`;
    }
  });
  return text;
  // router.push({ path: '/login' });
};
const handlemouse = (e: string) => {
  const nav = document.getElementById(e);
  var flag;
  var downX; // 鼠标点击的x下标
  var scrollLeft; // 当前元素滚动条的偏移量
  nav.addEventListener('mousedown', function (event) {
    flag = true;
    downX = event.clientX; // 获取到点击的x下标
    scrollLeft = this.scrollLeft; // 获取当前元素滚动条的偏移量
    event.stopPropagation();
  });
  nav.addEventListener('mousemove', function (event) {
    if (flag) {
      // 判断是否是鼠标按下滚动元素区域
      var moveX = event.clientX; // 获取移动的x轴
      var scrollX = moveX - downX; // 当前移动的x轴下标减去刚点击下去的x轴下标得到鼠标滑动距离
      this.scrollLeft = scrollLeft - scrollX; // 鼠标按下的滚动条偏移量减去当前鼠标的滑动距离
      // console.log(scrollX);
      event.stopPropagation();
    }
  });

  nav.addEventListener('touchmove', function (event) {
    event.stopPropagation();
    nav.addEventListener(
      'touchmove',
      function (event) {
        event.preventDefault(); // 阻止默认的滚动行为
        var touch = event.targetTouches[0];
        var deltaX = touch.clientX - startX; // 计算滚动的距离
        container.scrollLeft -= deltaX; // 将盒子滚动相应的距离
        startX = touch.clientX; // 更新触摸点的位置
      },
      { passive: false },
    );
    // event.stopPropagation(); // 阻止事件冒泡
    // event.preventDefault(); // 阻止默认滚动事件
    // const touch = event.touches[0]; // 获取第一个触点
    // box.scrollTop += startY - touch.clientY; // 移动盒子
    // startY = touch.clientY; // 重置起始位置
  });
  const handler = (event: any) => {
    // 获取滚动方向
    const detail = event.wheelDelta || event.detail;
    // 定义滚动方向，其实也可以在赋值的时候写
    const moveForwardStep = 1;
    const moveBackStep = -1;
    // 定义滚动距离
    let step = 0;
    // 判断滚动方向,这里的100可以改，代表滚动幅度，也就是说滚动幅度是自定义的
    if (detail < 0) {
      step = moveForwardStep * 100;
    } else {
      step = moveBackStep * 100;
    }
    // 对需要滚动的元素进行滚动操作
    nav.scrollLeft += step;
    event.stopPropagation();
  };

  nav.addEventListener('mousewheel', handler, false);

  // 鼠标抬起停止拖动
  nav.addEventListener('touchmove', function (event) {
    event.stopPropagation(); // 阻止事件冒泡
    event.preventDefault(); // 阻止默认滚动事件
  });
  nav.addEventListener('mouseup', function (event) {
    flag = false;
    event.stopPropagation();
  });
  // 鼠标离开元素停止拖动
  nav.addEventListener('mouseleave', function (event) {
    flag = false;
    event.stopPropagation();
  });
};
const isAnyElementOutOfParent = (parentElement, positionedElementsSelector) => {
  //循环判断是否有一个元素超出了父元素

  var positionedElements = parentElement.querySelectorAll(positionedElementsSelector);

  for (var i = 0; i < positionedElements.length; i++) {
    if (isElementOutOfParent(positionedElements[i])) {
      return true; // 如果有任何一个元素超出了父级元素，返回true
    }
  }
  return false; // 所有元素都没有超出父级元素，返回false
};
const isElementOutOfParent = (element) => {
  //判断当前元素是否超出父元素
  var parentRect = element.parentNode.getBoundingClientRect();
  var elementRect = element.getBoundingClientRect();
  // console.log(element.offsetWidth,element.parentNode.offsetWidth)
  // return elementRect.left < parentRect.left?elementRect.right:false;
  return elementRect.left < parentRect.left || elementRect.right > parentRect.right - 20;
};
const getParentLeftList = (parentElement, positionedElementsSelector) => {
  //循环获取当前所有的定位元素
  let arr = 0; //当前判断需要削减的宽度
  var positionedElements = parentElement.querySelectorAll(positionedElementsSelector);
  for (var i = 0; i < positionedElements.length; i++) {
    if (i === 0) {
      arr = getParentLeftItem(positionedElements[i]);
    } else {
      if (arr > getParentLeftItem(positionedElements[i])) {
        arr = getParentLeftItem(positionedElements[i]);
      }
    }

    // if (isElementOutOfParent(positionedElements[i])) {

    // }
  }
  // console.log(arr)
  return arr; // 所有元素都没有超出父级元素，返回false
};
const getParentLeftItem = (element) => {
  //判断当前元素是否超出父元素
  var parentRect = element.parentNode.getBoundingClientRect();
  var elementRect = element.getBoundingClientRect();
  let delNumber: number =
    element.offsetLeft + elementRect.width - parentRect.width > 0
      ? 0
      : Math.abs(element.offsetLeft + elementRect.width - parentRect.width);

  // console.log(element.offsetLeft+elementRect.width)

  return delNumber - 20; //(element.offsetLeft,elementRect.width) - parentRect.width
  // console.log(element.offsetWidth,element.parentNode.offsetWidth)
  // return elementRect.left < parentRect.left?elementRect.right:false;
  // return elementRect.left < parentRect.left || elementRect.right > parentRect.right-20;
};
const addParentWidths = (parentElement: any, width: any, childInfo: any) => {
  if (parentElement) {
    var parentRect = parentElement.getBoundingClientRect();
    let widths = getDraggableNumber(width);
    // console.log(parentRect.width,widths,childInfo.x)
    // console.log((childInfo.x+width)-parentRect.width)
    return parentRect.width - (childInfo.x + widths);
  }

  // parentRect.width-(childInfo.x+width)
};
let cancatUrl: string = 'https://t-www.youxinjiyi.com/ex/#/';
let frcancatUrl: string = 'https://t-www.youxinjiyi.com/fr/#/';
let linkurl: string = 'https://t-www.youxinjiyi.com';
let workbenchUrl: string = 'http://t-workbench.youxinjiyi.com/#/';
let doorUrl: string = 'https://t-www.youxinjiyi.com/';
if (import.meta.env.MODE !== 'development') {
  cancatUrl = 'https://www.jiyi.show/ex/#/';
  frcancatUrl = 'https://www.jiyi.show/fr/#/';
  linkurl = 'https://www.jiyi.show';
  workbenchUrl = 'https://workbench.jiyi.show/#/';
  doorUrl = 'https://www.jiyi.show/';
}
const publicUrls: string = 'https://static.jiyi.show/';
const outLogin = (e: string): any => {
  // window.location.href = e;
  router.push({ path: '/login' });
};
const getUrlTemplateId = () => {
  const url = window.location.href;
  const regex = /\/(\d+)/; // 匹配数字参数的正则表达式
  const match = url.match(regex); // 使用正则表达式匹配数字参数

  if (match) {
    const numericParam = parseInt(match[1]); // 提取数字参数并将其转换为数字类型
    // alert(numericParam);
    // console.log(numericParam); // 输出数字参数的值
    localStorage.setItem('projectId', String(numericParam));
    return numericParam;
  } else {
    return;
    // window.location.href = doorUrl;
  }
};
const removeLottie = () => {
  var element: any = document.getElementById('animationElement-lottieMove');
  var parent = element.parentNode;
  setTimeout(() => {
    element.style.opacity = 0;
  }, 600);

  setTimeout(() => {
    // parent.removeChild(element);
    element.remove();
  }, 1600);
};
const pathSquare = () => { };
const getdraggableDisabled = (loopType: boolean, disabled?: boolean) => {
  if (loopType) {
    return false;
  } else if (!loopType && !disabled) {
    return false;
  } else {
    return true;
  }
};
const formatFileSize = (size: any) => {
  if (size >= 1024) {
    return (size / 1024).toFixed(1) + 'M';
  } else {
    return size.toFixed(1) + 'K';
  }
};
const psthOutline = (id: string) => {
  //通过元素滚动到指定单元函数
  // Level1outline505056006086725
  var element = document.getElementById(id);
  // console.log(element.offsetLeft);
  let parentElement = document.getElementById('edit-scroll-box');
  // parentElement.scrollLeft = element.offsetLeft;
  const targetRect = element.getBoundingClientRect();
  const containerRect = parentElement.getBoundingClientRect();

  // 计算滚动距离，确保目标元素在容器中心位置
  const scrollOffset =
    targetRect.left - containerRect.left + parentElement.scrollLeft - containerRect.width / 2 + targetRect.width / 2;
  console.log(scrollOffset, '获取当前最后');
  // 设置滚动容器的滚动位置
  parentElement.scrollLeft = scrollOffset;
  // element.scrollIntoView({ behavior: 'smooth', block: 'start' });
};

// 超过字数文本换行
const textType = (str: string, max: number = 8) => {
  if (str) {
    var symbol = 0;
    var punctuationRegex = /[!"#$%&'()*+,-.\/:;<=>?@[\]^_`{|}~，。、；：？！…【】（）《》“”‘’￥]/g;
    // 使用 match 方法获取匹配的结果数组，并返回其长度
    var punctuationMatches = str.match(punctuationRegex);

    // 如果没有匹配到标点符号，返回 0；否则返回匹配到的标点符号数量
    if (punctuationMatches) {
      symbol = punctuationMatches.length;
    } else {
      symbol = 0;
    }

    if (str?.length <= max) {
      return `<p>${str}</p>`;
    } else if (str?.length % 2 == 0) {
      return `<p>${str.substring(0, str?.length / 2)}</p><p>${str.substring(
        str?.length + symbol,
        str?.length / 2,
      )}</p>`;
    } else {
      return `<p>${str.substring(0, Math.ceil(str?.length / 2))}</p><p>${str.substring(
        str?.length,
        Math.ceil(str?.length / 2),
      )}</p>`;
    }
  } else {
    return '';
  }
};
const getTextHtmlellipsisBr = (e: string | null): any => {
  if (!e) {
    return;
  }
  let arr = e.split('\n');
  let text = '';
  arr.forEach((el, index) => {
    if (el && index !== 0) {
      text = text + `\n      ${el}`;
    } else {
      text = text + `${el}`;
    }
  });
  return text;
  // router.push({ path: '/login' });
};
const isURL = (input) => {
  // 匹配URL的正则表达式
  var urlPattern = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i;

  // 判断输入是否匹配正则表达式
  return urlPattern.test(input);
};
const getRemarksNum = (num: number, type: boolean) => {
  //获取描述显示排数
  if (type) {
    return num;
  } else {
    return num - 1;
  }
};
const dataURLtoFile = (dataurl, filename) => {
  let arr = dataurl.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, {
    type: mime,
  });
};
export {
  dataURLtoFile,
  getRemarksNum,
  getTextHtmlellipsisBr,
  isURL,
  psthOutline,
  formatFileSize,
  pathSquare,
  removeLottie,
  getUrlTemplateId,
  outLogin,
  doorUrl,
  workbenchUrl,
  linkurl,
  cancatUrl,
  publicUrls,
  frcancatUrl,
  addParentWidths,
  getTextHtml,
  addBrowseTemplate,
  filterHTML,
  isAnyElementOutOfParent,
  isElementOutOfParent,
  getParentLeftList,
  getParentLeftItem,
  handlemouse,
  getdraggableDisabled,
  textType,
};
